package com.sskj.givecoin.v.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.sskj.givecoin.R;
import com.sskj.givecoin.common.App;
import com.sskj.givecoin.common.MarketWebSocket;
import com.sskj.givecoin.common.widget.ToolBarLayout;
import com.sskj.givecoin.m.HttpConfig;
import com.sskj.givecoin.m.bean.bean.NewStock;
import com.sskj.givecoin.m.bean.bean.Stock;
import com.sskj.givecoin.p.activity.MarketPresenter;
import com.sskj.givecoin.utils.ClickUtil;
import com.sskj.givecoin.utils.GsonUtil;
import com.sskj.givecoin.utils.NumberUtil;
import com.sskj.givecoin.v.base.BaseActivity;
import com.sskj.givecoin.v.base.BaseFragment;
import com.sskj.givecoin.v.fragment.ChartFragment;
import com.sskj.givecoin.v.fragment.SummaryFragment;
import com.sskj.givecoin.v.fragment.TradeFragment;
import com.sskj.givecoin.v.widget.mychart.KChartPop;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MarketDetailActivity extends BaseActivity<MarketPresenter> {

    @BindView(R.id.priceNow)
    TextView mPriceNow;
    @BindView(R.id.changeRate)
    TextView mChangeRate;
    @BindView(R.id.highText)
    TextView mHighText;
    @BindView(R.id.highPrice)
    TextView mHighPrice;
    @BindView(R.id.lowText)
    TextView mLowText;
    @BindView(R.id.lowPrice)
    TextView mLowPrice;
    @BindView(R.id.market_info)
    RelativeLayout mMarketInfo;
    @BindView(R.id.marketFrame)
    FrameLayout mMarketFrame;
    @BindView(R.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.market_viewpager)
    ViewPager mMarketViewpager;
    @BindView(R.id.marketTab)
    TabLayout marketTab;
    @BindView(R.id.marketToolBar)
    ToolBarLayout toolbar;
    @BindView(R.id.marketcCnyPrice)
    TextView marketcCnyPrice;  // 人民币价钱
    private MarketWebSocket webSocket;
    @BindView(R.id.marketBuy)
    TextView mMarketBuy;
    @BindView(R.id.marketSale)
    TextView mMarketSale;
    @BindView(R.id.appbarlayout)
    AppBarLayout mAppbarlayout;
    @BindView(R.id.tvParam)
    TextView tvParam;

    //当前币
    private NewStock mStock;

    //要跳转的fragment的index
    private int index;


    private ArrayList<BaseFragment> mFragments = new ArrayList();
    private String[] mTitles = new String[]{App.INSTANCE.getString(R.string.strMarketDetailActivity200), App.INSTANCE.getString(R.string.strMarketDetailActivity201)};

    //K线相关
    private int currentIndex = 0;
    private MyFragmentPagerAdapter mPagerAdapter;
    private ArrayList<ChartFragment> fragmentList = new ArrayList<>();
    //    String[] goodsType = {"minute", "minute", "minute5", "minute15", "minute30", "day"};
    String[] goodsType = {"minute", "minute5", "minute15", "minute30", "minute60", "day"};
    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private DecimalFormat priceFormat = new DecimalFormat("0.0000");
    private KChartPop kChartPop;
    private boolean isUpToggle = true;
    private boolean isDownToggle = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_market_new;
    }

    @Override
    public MarketPresenter getPresenter() {
        return new MarketPresenter();
    }

    @Override
    protected void initView() {
        mStock = (NewStock) getIntent().getSerializableExtra("stock");
        index = getIntent().getIntExtra("index", 0);
        //============title=========================
        String name[] = mStock.getName().split("_");
        if (name != null) {
            toolbar.setTitle(name[0]);
        } else {
            toolbar.setTitle(mStock.getName());
        }

        toolbar.setLeftButtonOnClickLinster(v -> finish());
//        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //===============交易和简介===========================
        mFragments.add(SummaryFragment.newInstance(mStock.getCode()));
        mFragments.add(TradeFragment.newInstance(mStock.getCode()));
        //================K线===================================
        mPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
        mMarketViewpager.setAdapter(mPagerAdapter);

        slidingTabLayout.setViewPager(mMarketViewpager,mTitles);

        initTab();
        //隐藏币币交易按钮
        mMarketBuy.setVisibility(View.GONE);
        ClickUtil.click(tvParam, () -> {
            if (kChartPop == null) {
                kChartPop = new KChartPop(this);
                View contentView = kChartPop.getContentView();
                TextView tvMa = contentView.findViewById(R.id.tvMa);
                TextView tvBoll = contentView.findViewById(R.id.tvBoll);
                TextView tvMacd = contentView.findViewById(R.id.tvMacd);
                TextView tvKdj = contentView.findViewById(R.id.tvKdj);
                TextView tvRsi = contentView.findViewById(R.id.tvRsi);
                TextView tvWr = contentView.findViewById(R.id.tvWr);
                ImageView ivUpToggle = contentView.findViewById(R.id.ivUpToggle);
                ImageView ivDownToggle = contentView.findViewById(R.id.ivDownToggle);
                ClickUtil.click(tvMa, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    ivUpToggle.setImageResource(R.mipmap.see);
                    kChartPop.dismiss();
                });
                ClickUtil.click(tvBoll, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawBollShow();
                    ivUpToggle.setImageResource(R.mipmap.see);
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivUpToggle, () -> {
                    if (isUpToggle) {
                        isUpToggle = false;
                        ivUpToggle.setImageResource(R.mipmap.unsee);

                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawNoneShow();
                    } else {
                        isUpToggle = true;
                        ivUpToggle.setImageResource(R.mipmap.see);
                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    }
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvMacd, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeMACD();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvKdj, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeKDJ();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvRsi, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeRSI();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvWr, () -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeWR();
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivDownToggle, () -> {
                    if (isDownToggle) {
                        isDownToggle = false;
                        ivDownToggle.setImageResource(R.mipmap.unsee);

                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    } else {
                        isDownToggle = true;
                        ivDownToggle.setImageResource(R.mipmap.see);

                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    }
                    kChartPop.dismiss();

                });
                kChartPop.setBackground(0);
            }
            if (kChartPop.isShowing()) {
                kChartPop.dismiss();
            } else {
                kChartPop.showPopupWindow(tvParam);
            }
        });
    }

    @Override
    protected void initData() {
        updateView(mStock);
        //币币交易
        ClickUtil.click(mMarketBuy, () -> {
            MainActivity.start(mActivity, 1, 0);
        });
        //合约交易
        ClickUtil.click(mMarketSale, () -> {
            MainActivity.start(mActivity, index, 0);
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (webSocket != null) {
            webSocket.closeWebSocket();
            webSocket = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webSocket == null) {
            openWebSocket();
        }
    }

    public void updateView(NewStock stock) {
        runOnUiThread(() -> {
            if (stock.getCode().equals(mStock.getCode())) {
                BigDecimal bigDecimal = new BigDecimal(stock.getPrice());
                if (stock.getChange() <= 0) {
                    mChangeRate.setTextColor(getResources().getColor(R.color.app_e76));
                    mPriceNow.setTextColor(getResources().getColor(R.color.app_e76));
                    mMarketSale.setBackground(getResources().getDrawable(R.drawable.shape_rectangle_red_rc));
                    marketcCnyPrice.setText("≈" + (TextUtils.isEmpty(stock.getCnyPrice()) ? "0.00" : NumberUtil.keep2(stock.getCnyPrice())) + " CNY");// 设置人民币

                } else {
                    mChangeRate.setTextColor(getResources().getColor(R.color.app_03c));
                    mPriceNow.setTextColor(getResources().getColor(R.color.app_03c));
                    mMarketSale.setBackground(getResources().getDrawable(R.drawable.shape_rectangle_green_rc));
                    marketcCnyPrice.setText("≈" + (TextUtils.isEmpty(stock.getCnyPrice()) ? "0.00" : ("+" + NumberUtil.keep2(stock.getCnyPrice()))) + " CNY");// 设置人民币

                }
                mChangeRate.setText(stock.getChangeRate().charAt(0)!='-'?("+"+stock.getChangeRate()):stock.getChangeRate());
                marketcCnyPrice.setText("≈" + (TextUtils.isEmpty(stock.getCnyPrice()) ? "0.00" : NumberUtil.keep2(stock.getCnyPrice())) + " CNY");// 设置人民币
                mHighPrice.setText(priceFormat.format(stock.getHigh()));
                mLowPrice.setText(priceFormat.format(stock.getLow()));
                mPriceNow.setText(NumberUtil.keepPoint4(stock.getPrice()));
                //更新分时线
                if (fragmentList.get(currentIndex) != null) {
                    fragmentList.get(currentIndex).socketPrice = stock.getPrice();
                    fragmentList.get(currentIndex).upDate(copyStock(stock));
                }

            }
        });
    }


    public Stock copyStock(NewStock newStock) {
        Stock stock = new Stock();
        try {
            long timeStamp = timeFormat.parse(newStock.getDate() + " " + newStock.getTime()).getTime();
            stock = new Stock(newStock.getCode(), newStock.getName(), newStock.getOpen(), newStock.getPrice(), newStock.getHigh(), newStock.getLow(), newStock.getVolume(), newStock.getDate(), newStock.getTime(), timeStamp / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return stock;
    }


    public void openWebSocket() {
        String url = HttpConfig.BTC_WS;
        JSONObject text = new JSONObject();
        try {
            text.put("code", mStock.getCode());
            if (webSocket != null) {
                webSocket.closeWebSocket();
            }
            webSocket = new MarketWebSocket(url, "MarketDetail", text.toString());
            webSocket.setListener(message -> {
                NewStock newStock = GsonUtil.GsonToBean(message, NewStock.class);
                updateView(newStock);
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    private void initTab() {
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        marketTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        selectTab(0);
    }

    /**
     * k线切换
     *
     * @param index
     */
    private void selectTab(int index) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ChartFragment minuteFragment = fragmentList.get(index);
        ChartFragment currentFragment = fragmentList.get(currentIndex);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        if (minuteFragment == null) {
            if (index == 0) {
                minuteFragment = ChartFragment.newInstance(mStock.getCode(), goodsType[index], true);
            } else {
                minuteFragment = ChartFragment.newInstance(mStock.getCode(), goodsType[index], false);
            }
            fragmentList.set(index, minuteFragment);
            ft.add(R.id.marketFrame, minuteFragment);
        } else {
            ft.show(minuteFragment);
        }
        ft.commit();
        currentIndex = index;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * @param context
     * @param stock
     * @param index   要跳转的页面
     */
    public static void start(Activity context, NewStock stock, int index) {
        Intent intent = new Intent(context, MarketDetailActivity.class);
        intent.putExtra("stock", stock);
        intent.putExtra("index", index);
        context.startActivity(intent);
    }


    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        private String[] title;
        private List<BaseFragment> views;

        public MyFragmentPagerAdapter(FragmentManager fm, String[] title, List<BaseFragment> views) {
            super(fm);
            this.title = title;
            this.views = views;
        }

        public MyFragmentPagerAdapter(FragmentManager fm, List<BaseFragment> views) {
            super(fm);
            this.views = views;
        }

        @Override
        public BaseFragment getItem(int position) {
            return views.get(position);
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        //配置标题的方法
        @Override
        public CharSequence getPageTitle(int position) {
            return title == null ? "" : title[position];
        }
    }

}
